package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.system.base.service.impl.JeecgServiceImpl;
import org.jeecg.modules.system.entity.BizBasicInfo;
import org.jeecg.modules.system.entity.BizWarehousing;
import org.jeecg.modules.system.mapper.BizBasicInfoMapper;
import org.jeecg.modules.system.mapper.BizWarehousingMapper;
import org.jeecg.modules.system.service.IBizWarehousingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 入库
 * @Author: jeecg-boot
 * @Date: 2024-02-01
 * @Version: V1.0
 */
@Service
public class BizWarehousingServiceImpl extends JeecgServiceImpl<BizWarehousingMapper, BizWarehousing> implements IBizWarehousingService {

    @Autowired
    private BizBasicInfoMapper bizBasicInfoMapper;


    @Autowired
    public RedisTemplate<String, Object> redisTemplate;


    @Override
    @Transactional
    public boolean save(BizWarehousing entity) {

        try {

            Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock_"+entity.getBaseicId(), 1);

            if (lock) {
                // 2.抢占成功，执行业务

                baseMapper.insert(entity);

                BizBasicInfo bizBasicInfo = bizBasicInfoMapper.selectById(entity.getBaseicId());

                bizBasicInfo.setInventoryQuantity(bizBasicInfo.getInventoryQuantity() + entity.getQty());
                bizBasicInfoMapper.updateById(bizBasicInfo);


                // 3.解锁
                redisTemplate.delete("lock");
                return false;

            } else {
                // 4.休眠一段时间
                Thread.sleep(200);
                System.out.println("locking");
                // 5.抢占失败，等待锁释放
                return save(entity);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return false;
    }



    @Override
    public IPage<BizWarehousing> getPageLIst(Page<BizWarehousing> page,BizWarehousing bizWarehousing) {
        IPage<BizWarehousing> pageList = baseMapper.getPageList(page,bizWarehousing);
        return pageList;
    }

    @Override
    public List<BizWarehousing> query(String c) {

        return baseMapper.query(c);
    }
}
